package store.lunangangster.engine.impl.helper;

import store.lunangangster.bpmn.model.Process;
import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.ProcessDefinitionEntity;
import store.lunangangster.engine.impl.entity.mgr.DeploymentManager;
import store.lunangangster.engine.impl.repository.ProcessDefinitionCacheEntry;
import store.lunangangster.engine.repository.ProcessDefinition;

public class ProcessDefinitionUtil {

  /**
   * 根据processDefinitionId找到其已经持久化的{@link ProcessDefinition}，并获取其对应的{@link Process}
   * @param processDefinitionId 流程定义id
   * @return 已经部署的Process对象
   */
  public static Process getProcess(String processDefinitionId) {
    DeploymentManager deploymentManager = Context.getCommandContext()
        .getProcessEngineConfiguration().getDeploymentManager();

    ProcessDefinition processDefinition = deploymentManager.findProcessDefinitionById(
        processDefinitionId);
    // resolve ProcessDefinition and get ProcessDefinitionCacheEntry
    ProcessDefinitionCacheEntry processDefinitionCacheEntry
        = deploymentManager.resolveProcessDefinition(processDefinition);
    return processDefinitionCacheEntry.getProcess();
  }

  public static void getExecutionEntityWithProcessDefinitionProperty(final ExecutionEntity execution) {
    ProcessDefinitionEntity processDefinitionEntity = Context.getProcessEngineConfiguration()
        .getProcessDefinitionEntityManager()
        .selectById(execution.getProcessDefinitionId());

    execution.setProcessDefinitionKey(processDefinitionEntity.getKey());
  }
}
